package com.android.base.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.base.R;
import com.android.base.utils.DisplayUtils;

public class BaseRecyclerView extends RecyclerView {
    //默认值
    private final static int DIVIDER_HEIGHT = 5;
    private final static boolean TOUCH_ABLE = true;
    private final static int DIVIDER_COLOR = Color.TRANSPARENT;
    private LinearLayoutManager mLayoutManager;
    private boolean touch;
    private int divider;
    private int color;
    private ProgressDialog progressDialog;
    public BaseRecyclerView(Context context) {
        super(context);
    }

    public BaseRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        handleAttrs(context, attrs);
        mLayoutManager = new LinearLayoutManager(context);
        this.setLayoutManager(mLayoutManager);
        this.setHasFixedSize(true);
        this.addItemDecoration(new BaseRecyclerDivider(
                context, LinearLayoutManager.VERTICAL, DisplayUtils.dp2px(divider),
                ContextCompat.getColor(context, color)));
    }

    private void handleAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BaseRecyclerView);
        divider = ta.getInt(R.styleable.BaseRecyclerView_divider, DIVIDER_HEIGHT);
        touch = ta.getBoolean(R.styleable.BaseRecyclerView_touchable, TOUCH_ABLE);
        color = ta.getInt(R.styleable.BaseRecyclerView_divider_color, DIVIDER_COLOR);
        ta.recycle();
    }


    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);

    }

    @Override
    public LinearLayoutManager getLayoutManager() {
        return mLayoutManager;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (!touch) {
            return false;
        }
        return super.onTouchEvent(ev);
    }

    public void moveToPosition(int n) {
        mLayoutManager.scrollToPositionWithOffset(n, 0);
        mLayoutManager.setStackFromEnd(true);
    }

    public void moveToPosition(RecyclerView mRecyclerView, int n) {
        int firstItem = mLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }
}
        

